package com.ctg.edas.demo;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;

@Configuration
public class FeignRequestInterceptor implements RequestInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(FeignRequestInterceptor.class);

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.isNull(attributes)) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        if (request != null) {
            String userToken = request.getHeader("userToken");
            logger.info("==userToken=" + userToken);

            Map<String, Collection<String>> headers = requestTemplate.headers();
            if (StringUtils.isNotBlank(userToken)) {
                if (CollectionUtils.isNotEmpty(headers.get("userToken"))) {
                    logger.info("==requestTemplate.userToken=before=" + headers.get("userToken").toString());
                }
                requestTemplate.removeHeader("userToken");
                requestTemplate.header("userToken", userToken);
                if (CollectionUtils.isNotEmpty(headers.get("userToken"))) {
                    logger.info("==requestTemplate.userToken=after=" + headers.get("userToken").toString());
                }
            }

            String cookie = request.getHeader("Cookie");
            logger.info("request.cookie====[{}]", cookie);
            requestTemplate.header("Cookie", cookie);

        }
    }
}
